<?php
namespace App\Controllers\admin;

/**
 * 授权管理
 */
class Auth extends \CodeIgniter\Controller
{

    /**
     * 登录
     */
    public function login()
    {
        $request = service('request');
        $data = [];
        helper('form');
        $admintor = model('admintor');
        if ($request->getMethod() == 'post') {
            // 登录验证
            $admintor = model('admintor');
            $rules = $admintor->getValidationRules([
                'only' => [
                    'username',
                    'password'
                ]
            ]);
            $rules['password']['rules'] .= '|valid_admintor[username,password]|valid_admintorStatus[username]';
            $rules['password']['errors'] = [
                'valid_admintor' => '用户名或密码不正确。',
                'valid_admintorStatus' => '该用户已被禁用。'
            ];
            if (! $this->validate($rules)) {
                $data['validation'] = $this->validator;
            } else {
                $model = model('admintor');
                $data = $model->where('username', $request->getVar('username'))
                    ->first();
                $admintor->setSession($data);
                // 添加闪存数据
                // $session->setFlashdata('success', '注册成功');
                return redirect()->route('index');
            }
        }
        echo view('admin/auth/header', $data);
        echo view('admin/auth/login');
        echo view('admin/auth/footer');
    }

    /**
     * 登出
     */
    public function logout()
    {
        session()->destroy();
        return redirect('login');
    }

    /**
     * 注册新用户
     */
    public function register()
    {
        $data = [];
        helper('form');
        $request = service('request');
        $admintor = model('admintor');
        $rules = $admintor->getValidationRules([]);
        if ($request->getMethod() == 'post') {
            // 处理注册
            $rules = $admintor->getValidationRules([]);
            $rules['username']['rules'] .= '|is_unique[admintor.username,id]';
            $rules['password_confirm'] = [
                'label' => '密码确认',
                'rules' => 'required|matches[password]'
            ];
            if (! $this->validate($rules)) {
                $data['validation'] = $this->validator;
            } else {
                $newData = [
                    'username' => $request->getVar('username'),
                    'status' => intval($request->getVar('status')),
                    'mobile' => $request->getVar('mobile'),
                    'realname' => $request->getVar('realname'),
                    'password' => $request->getVar('password'),
                    'desc' => $request->getVar('desc')
                ];
                $admintor->save($newData);
                $session = session();
                $session->setFlashdata('success', '注册成功');
                return redirect()->route('login');
            }
        }
        // 显示注册页
        echo view('admin/auth/header', $data);
        echo view('admin/auth/register');
        echo view('admin/auth/footer');
    }

    /**
     * 修改个人资料
     */
    public function profile()
    {
        $data = [];
        helper('form');
        $admintor = model('admintor');
        if ($this->request->getMethod() == 'post') {
            $rules = $admintor->getValidationRules([]);
            unset($rules['username'], $rules['status']);
            if ($this->request->getPost('password') != '') {
                $rules['password_confirm'] = [
                    'label' => '密码确认',
                    'rules' => 'matches[password]'
                ];
            } else {
                unset($rules['password']);
            }
            
            if (! $this->validate($rules)) {
                $data['validation'] = $this->validator;
            } else {
                $newData = [
                    'id' => session()->get('id'),
                    'realname' => $this->request->getPost('realname'),
                    'mobile' => $this->request->getPost('mobile'),
                    'desc' => $this->request->getPost('desc'),
                    'status' => $this->request->getPost('status')
                ];
                if ($this->request->getPost('password') != '') {
                    $newData['password'] = $this->request->getPost('password');
                }
                $admintor->save($newData);
                session()->setFlashdata('success', '修改成功');
                return redirect()->route('profile');
            }
        }
        $data['user'] = $admintor->find(session()->get('id'));
        echo view('admin/auth/header', $data);
        echo view('admin/auth/profile');
        echo view('admin/auth/footer');
    }

    /**
     * 后台的修改密码
     */
    public function password()
    {
        if ($this->request->getMethod() == 'post') {
            helper('funcs');
            $admintor = model('admintor');
            $rules = $admintor->getValidationRules([
                'only' => [
                    'password'
                ]
            ]);
            $rules['oldPassword'] = [
                'label' => '当前密码',
                'rules' => 'required|min_length[6]|max_length[32]'
            ];
            $rules['password_confirm'] = [
                'label' => '密码确认',
                'rules' => 'required|matches[password]'
            ];
            $model = model('admintor')->find(session()->get('id'));
            if (! $model)
                error('请先登录！');
            
            if (! password_verify(sha1(md5($this->request->getPost('oldPassword'))), $model['password_hash'])) {
                error('当前密码不正确！');
            }
            if (! $this->validate($rules)) {
                error($this->validator->listErrors());
            }
            $newData = [
                'id' => session()->get('id'),
                'password' => $this->request->getPost('password')
            ];
            $admintor->save($newData);
            success();
        }
        return view('admin/auth/password');
    }

    /**
     * 后台的基本资料修改
     */
    public function info()
    {
        $request = service('request');
        if ($request->getMethod() == 'post') {
            $admintor = model('admintor');
            helper('funcs');
            $rules = $admintor->getValidationRules([
                'only' => [
                    'realname',
                    'mobile',
                    'status',
                    'desc'
                ]
            ]);
            if (! $this->validate($rules)) {
                error($this->validator->listErrors());
            } else {
                $newData = [
                    'id' => session()->get('id'),
                    'realname' => $this->request->getPost('realname'),
                    'mobile' => $this->request->getPost('mobile'),
                    'desc' => trim($this->request->getPost('desc')),
                    'status' => intval($this->request->getPost('status'))
                ];
                $admintor->save($newData);
                // 刷新session
                $admintor->setSession(model('admintor')->find(session()->get('id')));
                success();
            }
        }
        $data = session()->get();
        return view('admin/auth/info', compact('data'));
    }
}